package mspbots.xero.data.core.reports;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.xero.common.ResultMsg;
import mspbots.xero.data.core.AbstractToolsUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * com.mspbots.core.cw.receivers.TenantUserReceiver
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/7/29
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class ReportsReceiver extends AbstractToolsUtil {

    private final ReportsRepository reportsRepository;

    @RabbitListener(queues = "xero.reports.sync")
    public void processMessage(ResultMsg resultMsg) {

        Reports data = Reports.builder()
                .tenantId(resultMsg.getTenantId())
                .xeroTenantId(resultMsg.getXeroTenantId())
                .name(resultMsg.getAction())
                .otherId(resultMsg.getId())
                .syncTime(resultMsg.getSyncDate())
                .updateTime(LocalDateTime.now())
                .extend(resultMsg.getEntity())
                .build();

        this.reportsRepository.findByTenantIdAndNameAndXeroTenantIdAndOtherId(resultMsg.getTenantId(),
                data.getName(), data.getXeroTenantId(), data.getOtherId())
                .switchIfEmpty(this.reportsRepository.save(data))
                .filter(old -> old.getUpdateTime().isBefore(data.getUpdateTime()))
                .map(result -> {
                    data.setId(result.getId());
                    data.setCreateTime(result.getCreateTime());
                    return data;
                })
                .flatMap(this.reportsRepository::save).block(Duration.ofSeconds(10));

    }

}
